﻿using NB.MGJ.Common;
using NB.MGJ.Common.Helper;
using NB.MGJ.Common.MVC;
using NB.MGJ.Common.OSS;
using NB.MGJ.Model;
using NB.MGJ.Model.AntiFake;
using NB.MGJ.Model.CodeManage;
using NB.MGJ.Service.AntiFake;
using NB.MGJ.Service.Origins;
using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NB.MGJ.Web.Controllers
{
    /// <summary>
    /// 防伪管理
    /// </summary>
    /// =======================================================================
    /// 类名：DemoService DemoController的备注：DemoService~1<br/>
    /// =======================================================================<br/>
    /// 更新履历<br/>
    /// 序号          更新日期          责任人           更新内容<br/>
    /// 001           2017/08/28       昝小念           查询统计<br/>
    /// 002           2017/09/04       昝小念           评价记录<br/>
    /// 003           2017/09/08       昝小念           假码回复<br/>
    /// 004          2017/09/12        昝小念           异常查询统计<br/>
    /// =======================================================================<br/>
    public partial class AntiFakeController : BaseController
    {
        public QueryStatisticsService _qsService { get; set; }
        public AppraiseListService _alService { get; set; }
        public QuerycatchService _qcService { get; set; }
        public ReplyPseudoCodeService _rpcService { get; set; }
        public OriginsTempletService _originsTempleteService { get; set; }
        public AntiFakeButtonService _AntiFakeButtonService { get; set; }

        public AntiFakeController()
        {
            _qsService = new QueryStatisticsService();
            _alService = new AppraiseListService();
            _qcService = new QuerycatchService();
            _rpcService = new ReplyPseudoCodeService();
            _originsTempleteService = new OriginsTempletService();
            _AntiFakeButtonService = new AntiFakeButtonService();
        }

        #region 查询记录

        #region 视图

        public ActionResult QueryStatistics()
        {
            return View();
        }

        #endregion 视图

        #region 导出EXCEl

        public ActionResult ExportExecl(DetailSearch Smodel)
        {
            var modal = _qsService.Enterparise(LogOnUser.EnterpriseId);
            var model = _qsService.GetAllQueryCodeLog(Smodel.Fw_SCode, modal.Code);
            var _byte_query = Excel.Exprot<CodeLog>(model.ToList(), new string[] { "防伪码", "查询IP", "查询地区", "查询时间", "查询城市" }, p =>
            {
                return new object[] {
				p.Fw_Code,
				p.QueryIp,
				p.QueryProvince,
				p.QueryTime,
				p.QueryCity
				};
            }, "antifake");
            return File(_byte_query, "application/octet-stream", string.Format("{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
        }

        #endregion 导出EXCEl

        #region 页面数据显示

        public JsonResult PageList(DetailSearch Smodel, int pageIndex = 1, int pageSize = 10)
        {
            var modal = _qsService.Enterparise(LogOnUser.EnterpriseId);
            var getcode = _qsService.search(LogOnUser.EnterpriseId);
            //判断表是否存在
            var HasForm = _qsService.HasFormService(getcode);
            if (HasForm == 0)
            {
                var res = "";
                return Json(res);
            }
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;

            if (LogOnUser.Distributor != 0)
            {
                pm.StrCondition = " and ChangeLoginID=" + LogOnUser.UserID;
            }
            else
            {
                if (LogOnUser.EnterpriseId != 1)
                {
                    if (string.IsNullOrEmpty(LogOnUser.JuniorEnterprise))
                    {
                        pm.StrCondition = "  EnterpriseId  in (0)";
                    }
                    else
                    {
                       
                        var encode = (modal.ID).ToString();
                        //var entcode = encode.Substring(0,AppConst.SubStrLen);
                        int entcode = int.Parse(encode);
                        pm.StrCondition += " EnterpriseId=" + entcode + "";
                    }
                }
                else { pm.StrCondition = " 1=1  "; }
            }
            pm.StrCondition += " and Valid=1 ";
           
            var model = _qsService.GetQueryCodeLogService(ref pm, modal.Code, Smodel);
            return Json(model,JsonRequestBehavior.AllowGet);
        }

        #endregion 页面数据显示

        #endregion 查询记录

        #region 异常查询记录

        #region 视图

        public ActionResult QueryCatch()
        {
            return View();
        }

        #endregion 视图

        #region 导出EXCEL

        public ActionResult ExeclExport(DetailSearch Smodel)
        {
            var modal = _qsService.Enterparise(LogOnUser.EnterpriseId);
            var model = _qcService.GetAllQuerycatch(Smodel.Fw_SCode, modal.Code);
            var _byte_catch = Excel.Exprot<CodeLog>(model.ToList(), new string[] { "防伪码", "查询日期", "查询时间", "查询省份", "查询地区", "查询者", "是否异常" }, q =>
            {
                return new object[] {
		q.Fw_Code,
		q.QueryTime,
		q.QueryTime,
		q.QueryProvince,
		q.QueryCity,
	    q.QueryIp,
		q.Valid
				};
            }, "Querycatch");
            return File(_byte_catch, "application/octet-stream", string.Format("{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
        }

        #endregion 导出EXCEL

        #region 数据显示

        public JsonResult QuerycatchList(DetailSearch Smodel, int pageIndex = 1, int pageSize = 10)
        {
            var modal = _qsService.Enterparise(LogOnUser.EnterpriseId);
            var getcode = _qsService.search(LogOnUser.EnterpriseId);
           
            var HasForm = _qsService.HasFormService(getcode);
            if (HasForm==0)
            {
                var res = "";
                return Json(res);
            }
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            if (LogOnUser.Distributor != 0)
            {
                pm.StrCondition = "  ChangeLoginID=" + LogOnUser.UserID;
            }
            else
            {
                if (LogOnUser.EnterpriseId != 1)
                {
                    if (string.IsNullOrEmpty(LogOnUser.JuniorEnterprise))
                    {
                        pm.StrCondition = "  EnterpriseId  in (0) AND ";
                    }
                 
                }
                else { pm.StrCondition = " 1=1 AND "; }
            }
            pm.StrCondition += " Valid=0 ";
           
            var model = _qsService.GetQueryCodeLogService(ref pm, modal.Code, Smodel);
            return Json(model);
        }

        #endregion 数据显示

        #region 评价记录

        #region 视图

        public ActionResult AppraiseList()
        {
            return View();
        }

        #endregion 视图

        #region 反馈

        public ActionResult feedback()
        {
            return View();
        }

        #endregion 反馈

        public ActionResult FeedbackList(AntiFake_FeedBack FeedBack)
        {
            FeedBack.FeedbackDate = DateTime.Now;
            return Json(_alService.AddFeedBack(FeedBack));
        }

        #endregion 评价记录

        #region 分页数据

        public ActionResult CommentPagerList(string wsearch, int pageIndex = 1, int pageSize = 10)
        {
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            if (LogOnUser.Distributor != 0)
            {
                { pm.StrCondition = "  ChangeLoginID=" + LogOnUser.UserID; }
            }
            else
            {
                if (LogOnUser.EnterpriseId != 1)
                {
                    if (string.IsNullOrEmpty(LogOnUser.JuniorEnterprise)) { pm.StrCondition = "  EnterpriseId  in (0)"; }
                    else { pm.StrCondition = "  EnterpriseId in (" + LogOnUser.JuniorEnterprise + ")"; }
                }
                else { pm.StrCondition = " 1=1"; }
            }
            pm.StrCondition += " and ViewDel=0 and  NickName like '%" + wsearch + "%' ";
          
            var model = _alService.GetACommentService(ref pm, wsearch);
            return Json(model);
        }

        #endregion 分页数据

        public int DelAppraiseList(int id)
        {
            int result = _alService.DelAppraiseListService(id, LogOnUser);
            return result;
        }

        #endregion 异常查询记录

        #region 假码查询回复设置

        #region 页面数据

        public ActionResult ReplyPseudoCode()
        {
            L.EntityModel.AntiFake_QueryReply r = new L.EntityModel.AntiFake_QueryReply();
            if (_rpcService.IsExistsByID(LogOnUser.EnterpriseId))
            {
                r = _rpcService.GetQueryReplyByID(LogOnUser.EnterpriseId);
            }
            else
            {
                r = new L.EntityModel.AntiFake_QueryReply();
                r.ID = 0;
                r.MessageContent = "";
                r.WebContent = "";
            }
            ViewBag.QueryReply_Page = r;
            return View();
        }

        #endregion 页面数据

        #region 文件保存

        public ActionResult FileUpload(HttpPostedFileBase file, string MessageContent, string WebContent)
        {
            L.EntityModel.AntiFake_QueryReply model = new L.EntityModel.AntiFake_QueryReply();
            var EnterpriseId = LogOnUser.EnterpriseId;
            int result = _rpcService.GetQueryReplyCount(EnterpriseId);
            var _file = file;
            if (_file != null) { 
            string filePath = string.Empty, filename = Guid.NewGuid().ToString("N") + "." + file.FileName.Split('.')[1];

            if (_file.ContentLength > 0)  // 如果有文件, 则保存到一个地址
            {
                OssManager.Instance.PutObject(filename, file.InputStream);
                filePath = OssManager.Instance.GetUrl(filename).Replace("http://", "https://");
                //保存数据
                model.TelFileUrl = filePath;
            }
            }
                model.MessageContent = MessageContent;
                model.WebContent = WebContent;
                model.ChangeDate = DateTime.Now;
                model.ChangeLoginID = LogOnUser.UserID;
                model.ChangeLoginName = LogOnUser.LoginName;
                model.ViewDel = 0;            
                model.EnterpriseId = LogOnUser.EnterpriseId;
                model = WipeNullHelper.WipeNull<L.EntityModel.AntiFake_QueryReply>(model);
                if (result == 0) //判断数据库有无数据，无做数据添加
                {
                    result = _rpcService.AddReplyPseudo(model);
                }
                else //有做数据更新
                {
                    result = _rpcService.UpdateReplyPseudo(model);
                }
           
            return Json(result);
        }

        #endregion 文件保存

        #region 上传文本信息

        public int InReadFile(int Id)
        {
            try
            {
                L.EntityModel.AntiFake_QueryReply model = _rpcService.GetQueryReplyByID(Id);
                if (model == null)
                    return 0;
                else
                {
                    StreamReader fsRead = new StreamReader(model.TelFileUrl, System.Text.Encoding.Default);
                    string code = fsRead.ReadLine().TrimEnd(',');//读取一行数据

                    int n = 1;
                    while (!fsRead.EndOfStream)
                    {
                        fsRead.ReadLine();
                        n++;
                    }
                    fsRead.Close();

                    var result = _rpcService.EditReplyPseudoCodeService(model);
                    return result;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion 上传文本信息

        #endregion 假码查询回复设置
    }
}